package com.mgy.db.sharding.strategy;

import com.mgy.db.TableRouter;
import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 基于hint的分库策略
 *
 * @author mgy
 */
public class DatabaseHintShardingAlgorithm implements HintShardingAlgorithm<TableRouter> {

    @Override
    public Collection<String> doSharding(final Collection<String> availableTargetNames, final HintShardingValue<TableRouter> shardingValue) {
        List<String> shardingList = new ArrayList<>(shardingValue.getValues().size());
        for (TableRouter router : shardingValue.getValues()) {
            String actualDataSource = router.getDsPrefix() + router.getDbNo();
            if (availableTargetNames.contains(actualDataSource)) {
                shardingList.add(actualDataSource);
            }
        }

        if (shardingList.isEmpty()) {
            throw new IllegalArgumentException("分库参数不正确");
        }
        return shardingList;
    }

}
